package com.glela.controller;

import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.*;
import com.glela.platform.model.request.RequestBalanceModel;
import com.glela.platform.model.request.RequestCouponModel;
import com.glela.platform.model.request.RequestUserModel;
import com.glela.platform.model.response.*;
import com.glela.platform.service.*;
import com.glela.platform.util.ParameterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 
* @ClassName: MyMoneyController 
* @Description: 我的钱包业务入口
* @author NingChongQing
* @date 2017年8月14日 上午9:00:00
 */
@Controller
@RequestMapping(value = "/myMoney")
public class MyMoneyController {
	private static Logger logger = LoggerFactory.getLogger(MyMoneyController.class);

	@Autowired
	private UserService userService;
	@Autowired
	private UserJournalService userJournalService;
	@Autowired
	private UserPointJournalService userPointJournalService;
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;
	@Autowired
	private UserRedPacketService userRedPacketService;
	
	/**
	 * 
	* **********************************************
	* @Title: myWallet 
	* @Description: 我的钱包
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年8月15日 下午18:00:00 
	* **********************************************
	 */
	@RequestMapping(value = "/myWallet", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> myWallet(@RequestBody RequestUserModel request) {
		try {
			if (ParameterUtils.validParams(request.getUserId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			User user = this.userService.getUserById(request.getUserId());
			if (null == user) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			UserMoney userMoney_Balance = this.userJournalService.getUserMoneyByUserIdAndType(request.getUserId(),1);
			UserMoney userMoney_Point = this.userJournalService.getUserMoneyByUserIdAndType(request.getUserId(),2);
			String isShowPoint = "yes";
			if (userMoney_Point.getNormalAmount().intValue() <= 0) {
				isShowPoint = "no";
				if (this.userJournalService.checkOnWayAmountNear30Days(request.getUserId()) > 0) {
					isShowPoint = "yes";
				}
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("balanceAmount", BigDecimal.valueOf(userMoney_Balance.getNormalAmount()).divide(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP).toString());
			map.put("isShowPoint", isShowPoint);
			map.put("pointAmount", userMoney_Point.getNormalAmount() + "");
			map.put("redPacketAmount", userRedPacketService.sumTotalRedPacketByUserId(request.getUserId()));
			map.put("couponAmount", this.userJournalService.getUserPromotionTotalAmountWhichNotUsed(request.getUserId()) + "");
			return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("获取<我的钱包>异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 * 
	* **********************************************
	* @Title: myPoint 
	* @Description: 我的积分
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年8月15日 下午18:00:00
	* **********************************************
	 */
	@RequestMapping(value = "/myPoint", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> myPoint(@RequestBody RequestUserModel request) {
		try {
			if (request.getUserId() == 0L) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20133), HttpStatus.OK);
			}
			User user = userService.getUser(request.getUserId());
			if (null == user) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			UserMoney userMoney = this.userJournalService.getUserMoneyByUserIdAndType(request.getUserId(),2);
			List<UserPointJournal> userPointJournalList = userPointJournalService.getMyPointListByPage(request.getUserId(),request.getStartIndex(), request.getPageSize());
			int count = 0;
			List<ResponseUserPointJournalModel> rupjmlist = new ArrayList<ResponseUserPointJournalModel>();
			if(userPointJournalList!=null&&userPointJournalList.size()>0){
				if(request.getPageNum() == 1 && userMoney.getFrozenAmount() > 0){
					UserPointJournal userPointJournal = new UserPointJournal();
					userPointJournal.setBusinessTypeName("冻结妆币");
					userPointJournal.setAmount(-Long.valueOf(userMoney.getFrozenAmount()));
					userPointJournal.setCreateTime(new Date());
					rupjmlist.add(new ResponseUserPointJournalModel(userPointJournal));
				}
				count = userPointJournalList.size();
				for(UserPointJournal userPointJournal : userPointJournalList){
					rupjmlist.add(new ResponseUserPointJournalModel(userPointJournal));
				}
			}
			// 请求网关支付接口链接
			String helpLink = this.baseRestrictionsService.getBaseRestrictionsForCache("mypoint_helplink").getName();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("helpLink",helpLink);
			map.put("pointAmount", userMoney.getNormalAmount()+"");
			map.put("pointList", new ResponsePageModel<ResponseUserPointJournalModel>(count, request.getPageSize(),request.getPageNum(), rupjmlist));
			return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("获取<我的积分>异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 * 
	* **********************************************
	* @Title: myCoupon 
	* @Description: 我的优惠券
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年8月15日 下午18:00:00
	* **********************************************
	 */
	@RequestMapping(value = "/myCoupon", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> myCoupon(@RequestBody RequestCouponModel request) {
		try {
			if (request.getUserId() == 0L) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20133), HttpStatus.OK);
			}
			User user = userService.getUser(request.getUserId());
			if (null == user) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			Long userId = request.getUserId();
			int pageLimit = request.getStartIndex();
			int pageSize = request.getPageSize();
			List<UserPromotion> userPromotionList = new ArrayList<UserPromotion>();
			int type = request.getType();
			if(type == 0){// 未使用（默认值）
				userPromotionList = userJournalService.getUserPromotionListWhichNotUsed(userId,pageLimit,pageSize);
			}else if(type == 1){// 已使用
				userPromotionList = userJournalService.getUserPromotionListWhichHasUsed(userId,pageLimit,pageSize);
			}else if(type == 2){// 已过期
				userPromotionList = userJournalService.getUserPromotionListWhichOverdue(userId,pageLimit,pageSize);
			}
			List<ResponseCouponModel> rcList = new ArrayList<ResponseCouponModel>();
			// 多张相同的优惠券需要拆开显示
			if (userPromotionList != null && userPromotionList.size() > 0) {
				for (UserPromotion userPromotion : userPromotionList) {
					for (int i = 0; i < userPromotion.getPromotionNumber(); i++) {
						rcList.add(new ResponseCouponModel(userPromotion));
					}
				}
			}
			int count = rcList == null ? 0 : rcList.size();
			return new ResponseEntity<>(new ResponseResultModel<>(new ResponsePageModel<ResponseCouponModel>(count,request.getPageSize(),request.getPageNum(),rcList)),HttpStatus.OK);
		} catch (Exception e) {
			logger.error("获取<我的优惠券>异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 * 
	* **********************************************
	* @Title: myBalance 
	* @Description: 我的余额
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年8月15日 下午18:00:00
	* **********************************************
	 */
	@RequestMapping(value = "/myBalance", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> myBalance(@RequestBody RequestBalanceModel request) {
		try {
			if (request.getUserId() == 0L) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20133), HttpStatus.OK);
			}
			User user = userService.getUser(request.getUserId());
			if (null == user) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date beginDate = null;
			if (!ParameterUtils.validParams(request.getBeginDate())) {
				beginDate = sdf.parse(request.getBeginDate()+" 00:00:00");
			}
			Date endDate = null;
			if (!ParameterUtils.validParams(request.getEndDate())) {
				endDate = sdf.parse(request.getEndDate()+" 23:59:59");
			}
			UserMoney userMoney = this.userJournalService.getUserMoneyByUserIdAndType(request.getUserId(),1);
			BigDecimal balanceAmount = BigDecimal.valueOf(userMoney.getNormalAmount()).divide(BigDecimal.valueOf(100)).setScale(2,RoundingMode.HALF_UP);
			List<UserJournal> userJournalList = this.userJournalService.getMyBalanceListByPage(request.getUserId(),beginDate,endDate,request.getStartIndex(), request.getPageSize());
			List<ResponseBalanceModel> rbmList = new ArrayList<ResponseBalanceModel>();
			int count = 0;
			if(userJournalList != null&& userJournalList.size() > 0){
				if(request.getPageNum() == 1 && userMoney.getFrozenAmount() > 0){
					UserJournal userJournal = new UserJournal();
					userJournal.setComment("冻结余额");;
					userJournal.setType("-");
					userJournal.setMoney(userMoney.getFrozenAmount().intValue());
					userJournal.setCreateTime(sdf.format(new Date()));
					userJournal.setOrderSn("");
					rbmList.add(new ResponseBalanceModel(userJournal));
				}
				count = userJournalList.size();
				for(UserJournal userJournal : userJournalList){
					rbmList.add(new ResponseBalanceModel(userJournal));
				}
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("balanceAmount", balanceAmount.toString());
			map.put("balanceList", new ResponsePageModel<ResponseBalanceModel>(count,request.getPageSize(),request.getPageNum(),rbmList));
			return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("获取<我的余额>异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
}
